package account.drools;

import java.util.ArrayList;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.logger.KnowledgeRuntimeLogger;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.runtime.StatefulKnowledgeSession;

public class DroolsEngine {
	
	private static KnowledgeBase getKnowledgeBase() {
		KnowledgeBuilder kbuilder = KnowledgeBuilderFactory
				.newKnowledgeBuilder();
		kbuilder.add(
				ResourceFactory
						.newUrlResource("http://localhost:8080/jptq_account/DroolsResources"),
				ResourceType.DRL);

		KnowledgeBuilderErrors errors = kbuilder.getErrors();
		if (errors.size() > 0) {
			System.out.println("error");
			for (KnowledgeBuilderError error : errors) {
				System.out.println(error);
			}
			// throw new IllegalArgumentException("Could not parse knowledge.");
		}
		KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();		
		kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
		return kbase;
	}
	
	public static void fireAllRules( ArrayList< ? extends Object > params ) {
		try {
		KnowledgeBase kbase = getKnowledgeBase();
		StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
		// ksession.addEventListener(new DebugAgendaEventListener());

		// ksession.addEventListener(new DebugWorkingMemoryEventListener());

		KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory
				.newConsoleLogger(ksession);
		for( Object obj : params ) {
			ksession.insert( obj );
		}
		ksession.fireAllRules();

		logger.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
